﻿using System;
using System.Collections.Generic;
using System.Linq;

using SharedGenomics.Core;
using SharedGenomics.Domain;
using SharedGenomics.Domain.Builders;
using SharedGenomics.Workbench.PresentationModel;
using SharedGenomics.Workbench.Views;

namespace SharedGenomics.Workbench.Presenters
{
    public class CMHJobOptionsPresenter : Presenter, IJobOptionsPresenter
    {
        private ICMHJobOptionsView _cmhView;
        private JobSubmissionPTO _presentationModel;

        public CMHJobOptionsPresenter(ICMHJobOptionsView view)
            : base(view)
        {
            this._cmhView = view;
        }

        public bool Validate()
        {
            this._presentationModel.ThrowIfNull<InvalidOperationException>("Presentation model has not been set on CMH presenter");
            return this._cmhView.SelectedStratificationColumn != null;
        }

        public JobInfo CreateJob()
        {
            return JobBuilder.NewJob(JobType.PCMH)
                .ForDataSet(this._presentationModel.SelectedDataSetId.Value)
                .WithDescription(this._presentationModel.Description)
                .WithPermutations(this._presentationModel.SelectedPermutationCount.Value)
                .StratifiedBy(this._cmhView.SelectedStratificationColumn)
                .ToAnalyse(this._presentationModel.SelectedPhenotype)
                .Build();
        }

        public JobSubmissionPTO PresentationModel
        {
            set
            {
                value.ThrowIfNull("PresentationModel");
                this._presentationModel = value;
                this._cmhView.StratificationColumns = value.StratificationColumns;
                value.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(PresentationModel_PropertyChanged);
            }
        }

        private void PresentationModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "StratificationColumns")
            {
                this._cmhView.StratificationColumns = this._presentationModel.StratificationColumns;
            }
        }
    }
}
